<?php

/**
 * Description of PostalCodeController
 *
 * @author Poh Nean
 */
class PostalCodeController extends PsController
{

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'users' => array('@'),
					)), parent::accessRules());
	}

	public function filters()
	{
		return CMap::mergeArray(parent::filters(), array(
					'ajaxOnly 
                + autocomplete'
		));
	}

	/**
	 * Find address details using OneMap with a given postal code.
	 * @param type $postcode 
	 */
	public function actionSearch($postcode)
	{
		$response = array();
		if (strlen($postcode) > 0) {
			$data = array();

			// Get onemap token
			$accessKey = Yii::app()->params['onemapAccessKey'];
			$href = "http://www.onemap.sg/API/services.svc/getToken?accessKEY=" . $accessKey;
			$result = file_get_contents($href);
			$result = json_decode(preg_replace('/(\w+):/i', '"\1":', $result), true);
			$token = $result['GetToken'][0]['NewToken'];

			$href = 'http://www.onemap.sg/API/Services.svc/ga?token=' . $token . '&sv=' . $postcode;
			$result = json_decode(preg_replace('/(\w+):/i', '"\1":', file_get_contents($href)), true);
			$geoAddrInfo = $result['GeoAddrInfo'][0];

			$streetRegex = '/(\d+\w{0,1})*([\w**\s*]+\d*)/';
			preg_match_all($streetRegex, $geoAddrInfo['HBRN'], $matches);

			$data['building_name'] = ucwords(strtolower($geoAddrInfo['BLDG_NAME']));
			$data['address_1'] = ucwords(strtolower($geoAddrInfo['HBRN']));
			$data['block'] = trim($matches[1][0]);
			$data['street'] = ucwords(strtolower(trim($matches[2][0])));
			$data['postal_code'] = $postcode;
			$data['country_id'] = 219;
			$data['country_code'] = "SGP";

			$response['result'] = 'success';
			$response['data'] = $data;
		} else {
			$response['result'] = 'failure';
		}

		print json_encode($response);
	}

	/**
	 * Find address details using the internal database with a given postal code.
	 * @param type $postcode 
	 */
	public function actionAutocomplete($postcode = '', $country_id = null, $term = '')
	{
		$response = array();

		if (strlen($postcode) > 0 || strlen($term) > 0) {
			$data = array();

			if (!isset($country_id) || $country_id == 219) {
				$criteria = array(
					'condition' => 'postal_code = :postcode',
					'params' => array(
						':postcode' => $postcode,
					),
				);

				$postalCode = PostalCode::model()->find($criteria);

				if ($postalCode != null) {
					$data = $postalCode->attributes;
					unset($data["id"]);

					$data['street'] = ucwords(strtolower($data['street']));
					if ($postalCode->show_building_name === '1') {
						$data['building_name'] = ucwords(strtolower($data['building_name']));
					} else {
						unset($data['building_name']);
					}

					$data['address_1'] = $data['block'] . ' ' . $data['street'];
					if ($postalCode->show_block === '1') {
						$data['address_1'] = 'Blk ' . $data['address_1'];
					}

					$data['country_id'] = 219;
					$data['country_code'] = 'SGP';
				}

				$response['result'] = 'success';
				$response['data'] = $data;
			} else {
				// foreign country
//				$data['building_name'] = '';
//				$data['address_1'] = '';
//				$data['block'] = '';
//				$data['street'] = '';
//				$data['postal_code'] = $postcode;
//				$data['country_id'] = $country_id;

				$response['result'] = 'failure';
				$response['errorMsg'] = 'Postcode search is not available for this country.';
			}
		} else {
			$response['result'] = 'failure';
		}
		
		print json_encode($response);
	}

	function actionSearchByBuilding($term = '')
	{
		$response = array();

		if (strlen($term) > 0 || strlen($term) > 0) {
			$criteria = new CDbCriteria();
			$criteria->select = 'building_name, street, district, GROUP_CONCAT(block ORDER BY ABS(block)) AS block, GROUP_CONCAT(postal_code ORDER BY postal_code) AS postal_code';
			$criteria->compare('building_name', $term, true);
			$criteria->group = 'building_name';
			$criteria->order = 'building_name ASC';

			$data = array();
			$postalCodes = PostalCode::model()->findAll($criteria);

			if (!empty($postalCodes)) {
				foreach ($postalCodes as $postalCode) {
					$data[] = array(
						'label' => ucwords(strtolower($postalCode['building_name'])),
						'building_name' => ucwords(strtolower($postalCode['building_name'])),
						'street' => ucwords(strtolower($postalCode['street'])),
						'district' => $postalCode['district'],
						'blocks' => $postalCode['block'],
						'postal_codes' => $postalCode['postal_code']
					);
				}
			}
			$response = $data;
		}

		print json_encode($response);
	}

}

?>
